<?php

namespace app\admin\controller\unilive;

use app\common\controller\Backend;
use EasyWeChat\Factory;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 直播间
 *
 * @icon fa fa-circle-o
 */
class Room extends Backend
{

    /**
     * Room模型对象
     * @var \app\admin\model\unilive\Room
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\unilive\Room;
        $this->view->assign("liveStatusList", $this->model->getLiveStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("screenTypeList", $this->model->getScreenTypeList());
        $this->view->assign("closeLikeList", $this->model->getCloseLikeList());
        $this->view->assign("closeGoodsList", $this->model->getCloseGoodsList());
        $this->view->assign("closeCommentList", $this->model->getCloseCommentList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 同步
     */
    public function sync()
    {
        try {
            $config = get_addon_config('unilive');
            $app = Factory::miniProgram($config);

            $roomsModel = new \app\admin\model\unilive\Room();
            $oldRooms = $roomsModel::column('id,anchor_wechat,cover_img_media_id,share_img_media_id,type,screen_type,close_like,close_goods,close_comment', 'roomid');
            $start = 0;
            $limit = 100;
            $insertData = [];
            while (1) {
                $rooms = $app->subscribe_message->httpPostJson('wxa/business/getliveinfo', ['start' => $start, 'limit' => $limit]);
                if (isset($rooms['errcode']) && $rooms['errcode'] == 0 && !empty($rooms['room_info'])) {
                    $rooms['room_info'];
                    foreach ($rooms['room_info'] as $room) {
                        $insertData[] = [
                            'id' => $oldRooms[$room['roomid']]['id'] ?? 0,
                            'roomid' => $room['roomid'],
                            'name' => $room['name'],
                            'cover_img' => $room['cover_img'],
                            'start_time' => $room['start_time'],
                            'end_time' => $room['end_time'],
                            'anchor_name' => $room['anchor_name'],
                            'goods' => json_encode($room['goods'], JSON_UNESCAPED_UNICODE),
                            'live_status' => $room['live_status'],
                            'share_img' => $room['share_img'],
                            'anchor_wechat' => $oldRooms[$room['roomid']]['anchor_wechat'] ?? '',
                            'cover_img_media_id' => $oldRooms[$room['roomid']]['cover_img_media_id'] ?? '',
                            'share_img_media_id' => $oldRooms[$room['roomid']]['share_img_media_id'] ?? '',
                            'type' => $oldRooms[$room['roomid']]['type'] ?? '',
                            'screen_type' => $oldRooms[$room['roomid']]['screen_type'] ?? '',
                            'close_like' => $oldRooms[$room['roomid']]['close_like'] ?? '',
                            'close_goods' => $oldRooms[$room['roomid']]['close_goods'] ?? '',
                            'close_comment' => $oldRooms[$room['roomid']]['close_comment'] ?? '',
                        ];
                        if (isset($oldRooms[$room['roomid']])) {
                            unset($oldRooms[$room['roomid']]);
                        }
                    }

                } else {
                    if (isset($rooms['errmsg'])) {
                        throw new Exception($rooms['errmsg']);
                    }
                    break;
                }
                if (isset($rooms['total']) && $rooms['total'] <= $limit) {
                    break;
                }
                $start = $limit;
                $limit = $limit + $limit;
            }
            $roomsModel->insertAll($insertData, 'REPLACE');

            if (!empty($oldRooms)) {
                $id = array_column($oldRooms, 'id');
                $id = implode(',', $id);
                $roomsModel->where('id in (' . $id . ')')->delete();
            }

            $this->success('成功');

        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    $config = get_addon_config('unilive');
                    $app = Factory::miniProgram($config);
                    $roomParams = [
                        "name" => $params['name'], //房间名字 最长17个汉字，1个汉字相当于2个字符
                        "coverImg" => $params['cover_img'], //填写mediaID，直播间背景图，图片规则：建议像素1080*1920，大小不超过2M，mediaID获取参考：https=>//developers.weixin.qq.com/doc/offiaccount/Asset_Management/New_temporary_materials.html）
                        "startTime" => strtotime($params['start_time']), // 直播计划开始时间，1.开播时间需在当前时间10min后，2.开始时间不能在6个月后
                        "endTime" => strtotime($params['end_time']),  //直播计划结束时间，1.开播时间和结束时间间隔不得短于30min，不得超过12小时
                        "anchorName" => $params['anchor_name'], // 主播昵称 最长15个汉字，1个汉字相当于2个字符
                        "anchorWechat" => $params['anchor_wechat'], //主播微信号，需通过实名认证，否则将报错
                        "shareImg" => $params['share_img'], //填写mediaID，直播间分享图，图片规则：建议像素800*640，大小不超过1M，mediaID获取参考：https=>//developers.weixin.qq.com/doc/offiaccount/Asset_Management/New_temporary_materials.html）
                        "type" => $params['type'], //直播类型，1：推流，0：手机直播
                        "screenType" => $params['screen_type'], //1：横屏，0：竖屏，自动根据实际视频分辨率调整
                        "closeLike" => $params['close_like'], //1：关闭点赞 0：开启点赞 ，关闭后无法开启
                        "closeGoods" => $params['close_goods'], //1：关闭货架 0：打开货架，关闭后无法开启
                        "closeComment" => $params['close_comment'] //1：关闭评论 0：打开评论，关闭后无法开启
                    ];
                    $room = $app->subscribe_message->httpPostJson('wxaapi/broadcast/room/create', $roomParams);

                    if (isset($room['errcode'])) {
                        if ($room['errcode'] != 0) {
                            $this->error($room['errmsg']);
                        }
                    } else {
                        throw new Exception($room);
                    }

                    $params['roomid'] = $room['roomId'];
                    $params['live_status'] = 102; // 默认未开始

                    $coverImg = \app\admin\model\unilive\Media::getByMediaId($params['cover_img']);
                    $shareImg = \app\admin\model\unilive\Media::getByMediaId($params['share_img']);
                    $params['cover_img_media_id'] = $params['cover_img'];
                    $params['cover_img'] = $coverImg['path'] ?? $params['cover_img'];
                    $params['share_img_media_id'] = $params['share_img'];
                    $params['share_img'] = $shareImg['path'] ?? $params['share_img'];

                    $result = false;
                    Db::startTrans();

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 复制
     */
    public function copy($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    $config = get_addon_config('unilive');
                    $app = Factory::miniProgram($config);
                    $roomParams = [
                        "name" => $params['name'], //房间名字 最长17个汉字，1个汉字相当于2个字符
                        "coverImg" => $params['cover_img'], //填写mediaID，直播间背景图，图片规则：建议像素1080*1920，大小不超过2M，mediaID获取参考：https=>//developers.weixin.qq.com/doc/offiaccount/Asset_Management/New_temporary_materials.html）
                        "startTime" => strtotime($params['start_time']), // 直播计划开始时间，1.开播时间需在当前时间10min后，2.开始时间不能在6个月后
                        "endTime" => strtotime($params['end_time']),  //直播计划结束时间，1.开播时间和结束时间间隔不得短于30min，不得超过12小时
                        "anchorName" => $params['anchor_name'], // 主播昵称 最长15个汉字，1个汉字相当于2个字符
                        "anchorWechat" => $params['anchor_wechat'], //主播微信号，需通过实名认证，否则将报错
                        "shareImg" => $params['share_img'], //填写mediaID，直播间分享图，图片规则：建议像素800*640，大小不超过1M，mediaID获取参考：https=>//developers.weixin.qq.com/doc/offiaccount/Asset_Management/New_temporary_materials.html）
                        "type" => $params['type'], //直播类型，1：推流，0：手机直播
                        "screenType" => $params['screen_type'], //1：横屏，0：竖屏，自动根据实际视频分辨率调整
                        "closeLike" => $params['close_like'], //1：关闭点赞 0：开启点赞 ，关闭后无法开启
                        "closeGoods" => $params['close_goods'], //1：关闭货架 0：打开货架，关闭后无法开启
                        "closeComment" => $params['close_comment'] //1：关闭评论 0：打开评论，关闭后无法开启
                    ];
                    $room = $app->subscribe_message->httpPostJson('wxaapi/broadcast/room/create', $roomParams);

                    if (isset($room['errcode'])) {
                        if ($room['errcode'] != 0) {
                            $this->error($room['errmsg']);
                        }
                    } else {
                        throw new Exception($room);
                    }

                    $params['roomid'] = $room['roomId'];
                    $params['live_status'] = 102; // 默认未开始

                    $coverImg = \app\admin\model\unilive\Media::getByMediaId($params['cover_img']);
                    $shareImg = \app\admin\model\unilive\Media::getByMediaId($params['share_img']);

                    $params['cover_img_media_id'] = $params['cover_img'];
                    $params['cover_img'] = $coverImg['path'] ?? $params['cover_img'];
                    $params['share_img_media_id'] = $params['share_img'];
                    $params['share_img'] = $shareImg['path'] ?? $params['share_img'];

                    $result = false;
                    Db::startTrans();

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 导入直播商品
     */
    public function addgoods($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");


            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                try {

                    $config = get_addon_config('unilive');
                    $app = Factory::miniProgram($config);
                    $roomParams = [
                        "ids" => $params['goodsId'], //数组列表，可传入多个，里面填写 商品ID
                        "roomId" => $row['roomid'], //房间id
                    ];
                    $room = $app->subscribe_message->httpPostJson('wxaapi/broadcast/room/addgoods', $roomParams);

                    if (isset($room['errcode'])) {
                        if ($room['errcode'] != 0) {
                            $this->error($room['errmsg']);
                        } else {

                            $data = [];
                            foreach ($params['goodsId'] as $key => $value) {
                                $data[] = [
                                    "name" => $params['name'][$key] ?? '',
                                    "cover_img" => $params['cover_img'][$key] ?? '',
                                    "url" => $params['url'][$key] ?? '',
                                    "price" => $params['price'][$key] ?? '',
                                    "price2" => $params['price2'][$key] ?? '',
                                    "price_type" => $params['price_type'][$key] ?? '',
                                ];
                            }
                            if(empty($row->goods)) {
                                $row->goods = json_encode($data, JSON_UNESCAPED_UNICODE);
                                $row->save();
                            } else {
                                // 由于暂时微信并没有单独获取单个房间的数据接口，
                                // 并且房间的goods信息没有goodsId等唯一信息，
                                // 为了保证数据能在本地显示，只能暂时调用sync方法，
                                // 以换取速度为代价让我们方便管理
                                $this->sync();
                            }

                            $this->success('已添加');
                        }
                    } else {
                        throw new Exception($room);
                    }

                } catch (ValidateException $e) {
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
